package cn.kgc.crowdfundingadmin02.controller;


import cn.kgc.crowdfundingadmin02.common.ResultEntity;
import cn.kgc.crowdfundingadmin02.pojo.Menu;
import cn.kgc.crowdfundingadmin02.service.MenuService;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author shkstart
 * @create 2020-02-27 19:40
 */
@RestController
public class MenuController {

    @Resource
    MenuService menuService;

    @RequestMapping("/menu/get/whole/tree")
    public ResultEntity<Menu> getWholeTree(){
        //查询所有树形节点用于组装  所有数据存储到menuList中
        List<Menu> menuList=menuService.getAll();
        //将menuList转换成 map集合形式
        Map<Integer,Menu> menuMap =new HashMap<>();

        for (Menu menu : menuList) {
            menuMap.put(menu.getId(),menu);
        }
        //申明存储更节点对象
        Menu root=null;

        for (Menu menu : menuList) {
            //如果父节点为null  把父节点存储root 中  继续运行  跳出
            if(menu.getPid()==null){
                root=menu;
                continue;
            }
            //是子节点从menuMap找到父节点,添加到父节点的子节点集合中
            menuMap.get(menu.getPid()).getChildren().add(menu);
        }
        return  ResultEntity.successWithoutData(root);
    }


    //增加
    @RequestMapping("/menu/save")
    public ResultEntity<String> menusave(Menu menu){
        menuService.saveMenu(menu);
        return ResultEntity.successWithoutData();
    }

    //修改前的查询
    @RequestMapping("/menu/get/{menuId}")
    public ResultEntity<Menu> menugetid(@PathVariable Integer menuId){
        Menu menuById = menuService.getMenuById(menuId);
        return  ResultEntity.successWithoutData(menuById);
    }
    //修改
    @RequestMapping("/menu/update")
    public ResultEntity<String> menuupdate( Menu menu){
        menuService.update(menu);
        return ResultEntity.successWithoutData();
    }

    //删除
    @RequestMapping("/menu/delete/{menuId}")
    public ResultEntity<String> menudelete(@PathVariable("menuId") Integer menuId){
        menuService.batchRemove(menuId);
        return ResultEntity.successWithoutData();
    }
}
